﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RapidWebDev.UI.DynamicPages;
using RapidWebDev.Common;
using RapidWebDev.Platform;
using TestCenter.Platform.Apis;
using TestCenter.Platform.DataModel;
using RapidWebDev.Common.Data;

namespace TestCenter.Platform.Web.DynamicPages
{
    public class TestCaseResultManagement : DynamicPage
    {
        protected static readonly IAuthenticationContext authenticationContext = SpringContext.Current.GetObject<IAuthenticationContext>();

        protected static readonly ITestCenterApi testCenterApi = SpringContext.Current.GetObject<ITestCenterApi>();

        protected static readonly IHierarchyApi hierarchyApi = SpringContext.Current.GetObject<IHierarchyApi>();

        public override QueryResults Query(QueryParameter parameter)
        {
            LinqPredicate predicate = parameter.Expressions.Compile();
            //Get HierarchyData By parentId
            string testsuiteid = string.Empty;
            if (!string.IsNullOrEmpty(authenticationContext.TempVariables["suite"].ToString()))
                testsuiteid = authenticationContext.TempVariables["suite"].ToString();
            else
                testsuiteid = Guid.Empty.ToString();

            //var q = hierarchyApi.GetAllChildren("2", new Guid(parentId));

            //IList<string> queryCode = new List<string>();
            //foreach (var tmp in q)
            //{
            //    queryCode.Add(tmp.Code);
            //}

            using (TestCenterDataContext ctx = DataContextFactory.Create<TestCenterDataContext>())
            {
                int recordCount;
                string sortExpression = null;
                if (parameter.SortExpression != null)
                    sortExpression = parameter.SortExpression.Compile();

                if (Kit.IsEmpty(sortExpression))
                    sortExpression = "CreatedOn DESC";

                var result = from tp in ctx.TestCaseResults
                             where tp.TestSuiteId.ToString() == testsuiteid
                             select tp;

                if (predicate != null && !Kit.IsEmpty(predicate.Expression))
                    result = result.Where(predicate.Expression, predicate.Parameters);
                recordCount = result.Count();

                List<TestCaseResult> ret = result.Skip(parameter.PageIndex * parameter.PageSize).Take(parameter.PageSize).ToList();

                return new QueryResults(recordCount, ret);
            }
        }

        public override void SetupContextTempVariables(IRequestHandler sender, SetupApplicationContextVariablesEventArgs e)
        {
            if (sender.Parameters["suite"] != null)
                authenticationContext.TempVariables["suite"] = new Guid(sender.Parameters["suite"]);
        }
    }
}
